<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="text" oninput="debounceInput(event)" />

    <script>
      // 防抖实现
      // 高频事件触发后，n 妙后只执行一次，如果n 秒内触发，重新计算时间
      // 场景：input 输入事件，频繁点击按钮获取请求资源
      const debounce = (fn, delay) => {
        let timer = null;
        return function () {
          const context = this;
          const args = arguments;
          timer && clearTimeout(timer); // 清除定时器
          timer = setTimeout(() => {
            fn.apply(context, args);
          }, delay);
        };
      };

      // 测试
      function onInput(e) {
        if (e.target.value) {
          console.log(e.target.value);
        }
      }
      let debounceInput = debounce(onInput, 300);
    </script>
  </body>
</html>
